""" 
原理介绍: https://zhuanlan.zhihu.com/p/339855039

"""

import machine
from machine import Pin
import time
from hcsr04 import HCSR04


class Hcsr04:
    def __init__(self, trigger_pin, echo_pin):
        # trigger 输出使能
        self.trigger = Pin(trigger_pin, Pin.OUT, pull=None)
        self.trigger.value(0)

        # echo 输入, 读取高电平时间
        self.echo = Pin(echo_pin, Pin.IN, pull=None)

    def get_distance_cm(self):
        self.trigger.value(0)
        time.sleep_us(5)
        # trigger发送一个10us的高电平信号
        self.trigger.value(1)
        time.sleep_us(10)
        self.trigger.value(0)

        # 检测echo引脚高电平持续时间
        pulse_time = machine.time_pulse_us(self.echo, 1, 60 * 1000)
        """ machine.time_pulse_us(pin, pulse_level, timeout_us)
        引脚
        1 表示测量高电平脉冲的持续时间
        脉冲时间 60ms
        """

        # 计算距离
        """
        距离=速度x时间
        速度=340m/s=34000mm/s=0.034cm/us
        时间=高电平时间/2
        """
        distance_cm = 0.034 * pulse_time / 2
        return distance_cm


hcsr04 = Hcsr04(trigger_pin=4, echo_pin=27)

if __name__ == "__main__":
    while True:
        distance = hcsr04.get_distance_cm()
        print("distance=%.2f cm" % (distance))
        time.sleep(1)
